<?php
class Login extends Model
{
    /**
     *
     * @var Smarty
     */
    protected $_at;

    /**
     *
     * @var Db
     */
    protected $_db;

    /**
     *
     * @var boolean
     */
    protected $_loggedIn;

    /**
     *
     * @var array
     */
    protected $_userData;

    /**
     *
     * @return string
     */
    public function action()
    {
        $this->loginUser();
        return "start";
    }

    public function loginUser()
    {
        if('login' == $this->getRequest('action')) {
            $this->_loggedIn = false;
            $name = $this->getPost('logName');
            $pass = md5($this->getPost('logPass'));
            error_log("name = " . $name . "\n");
            error_log("pass = " . $pass . "\n");


            $q = 'SELECT name, password FROM Users WHERE name="' . $name . '" AND password="' . $pass . '"';
            $row = $this->getDb()->queryArray($q);
            $this->_userData = $row;

            if(0 < count($row) && isset($row['password'])) {
                error_log("got sql query \n");
                $_SESSION['logged'] = $row['password'];
                $_SESSION['name'] = $row['name'];
                ob_start();
                print_r('$_SESSION  = ');
                print_r($_SESSION );
                print_r("\n");
                $text = ob_get_clean();
                error_log($text);
                $this->_loggedIn = true;
                $this->getAt()->assign('loggedIn', $this->_loggedIn);
            }
        }
    }

    /**
     * @return Smarty
     */
    public function getAt()
    {
        if (!$this->_at) {
            $this->_at = Controller::getActionTemplate("localhost");
        }
        return $this->_at;
    }

    /**
     *
     * @param Smarty $at
     */
    public function setAt(Smarty $at)
    {
        $this->_at = $at;
    }

    /**
     *
     * @return MyDb
     */
    public function getDb()
    {
        if (!$this->_db) {
            $this->_db = Controller::getDatabase("localhost");
        }
        return $this->_db;
    }

    /**
     *
     * @param MyDb $db
     */
    public function setDb(Db $db)
    {
        $this->_db = $db;
    }

    public function getRequest($identifier = '') {
        if(empty($identier)) {
            $request = $_REQUEST;
        } else {
            $request = $_REQUEST[$identifier];
        }
        return $request;
    }

    /**
     *
     * @return array
     */
    public function getUserData() {
        return $this->_userData;
    }

    public function getPost($identifier = '') {
        if(empty($identier)) {
            $request = $_POST;
        } else {
            $request = $_POST[$identifier];
        }
        return $request;
    }
}

